﻿using FreeSql;
using FsCms.Service.Helper;
using System;
using System.Diagnostics;

namespace FsCms.Service.DAL
{
    public static class Db
    {
        public static System.Collections.Generic.Dictionary<string, IFreeSql> ConnectionPool = new System.Collections.Generic.Dictionary<string, IFreeSql>();

        private static string getConnectionString(string sDatabaseType)
        {
            return AppSettingsManager.Get($"DbContexts:{sDatabaseType}:ConnectionString");
        }

        private static IFreeSql SelectDBType(DataType enum_dbtype)
        {
            var dbtype = enum_dbtype.ToString();
            if (!ConnectionPool.ContainsKey(dbtype))
            {
                //IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                //    .UseConnectionString(enum_dbtype, getConnectionString(dbtype))
                //    //.UseSlave("connectionString1", "connectionString2") //使用从数据库，支持多个
                //    .UseMonitorCommand(
                //        cmd => Console.WriteLine(cmd.CommandText), //监听SQL命令对象，在执行前
                //        (cmd, traceLog) => Console.WriteLine(traceLog)) //监听SQL命令对象，在执行后
                //    .UseLogger(null) //使用日志，不指定默认输出控制台 ILogger
                //    .UseCache(null) //使用缓存，不指定默认使用内存 IDistributedCache
                //    .UseAutoSyncStructure(true) //自动同步实体结构到数据库
                //    .UseSyncStructureToLower(true) //转小写同步结构
                //    .UseLazyLoading(true) //延时加载导航属性对象，导航属性需要声明 virtual
                //    .Build();
                //ConnectionPool.Add(dbtype, fsql);

                ConnectionPool.Add(dbtype, new FreeSql.FreeSqlBuilder()
                     .UseConnectionString(enum_dbtype, getConnectionString(dbtype))
                     .UseAutoSyncStructure(true)
                     .UseMonitorCommand(
                        cmd =>
                        {
                            Trace.WriteLine(cmd.CommandText);
                        }, //监听SQL命令对象，在执行前
                        (cmd, traceLog) =>
                        {
                            Console.WriteLine(traceLog);
                        }) //监听SQL命令对象，在执行后
                    .UseLazyLoading(true)
                    .Build());
            }
            return ConnectionPool[dbtype];
        }

        public static IFreeSql DB(this DataType t)
        {
            return SelectDBType(t);
        }
    }
}
